import MarkdownIt from "markdown-it";
import hljs from "highlight.js";

const md = new MarkdownIt({
  html: false,
  linkify: true,
  highlight: (str, lang) => {
    const decodedStr = decodeHtmlEntities(str);
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${
          hljs.highlight(decodedStr, { language: lang }).value
        }</code></pre>`;
      } catch (_) {}
    }
    return `<pre class="hljs"><code>${
      hljs.highlightAuto(decodedStr).value
    }</code></pre>`;
  },
});

function decodeHtmlEntities(text: string) {
  return text
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, "&");
}

export const renderMarkdown = (content: string) => {
  // 临时替换代码块保护内容
  const codeBlocks: string[] = [];
  const tempContent = content.replace(/```[\s\S]*?```/g, (match) => {
    // 保留原始代码块内容
    codeBlocks.push(match);
    return `\uE000${codeBlocks.length - 1}\uE001`;
  });

  // 渲染非代码部分
  let rendered = md.render(tempContent);

  // 恢复代码块，确保保留原始格式
  rendered = rendered.replace(/\uE000(\d+)\uE001/g, (_, index) => {
    const codeBlock = codeBlocks[parseInt(index)];
    // 提取语言和代码内容
    const langMatch = codeBlock.match(/^```(\w*)\n/);
    const lang = langMatch ? langMatch[1] : "";
    const codeContent = codeBlock
      .replace(/^```(\w*)\n/, "")
      .replace(/\n```$/, "");

    // 使用highlight.js高亮代码
    try {
      const highlighted =
        lang && hljs.getLanguage(lang)
          ? hljs.highlight(codeContent, { language: lang }).value
          : hljs.highlightAuto(codeContent).value;

      return `<pre class="hljs"><code class="language-${lang}">${highlighted}</code></pre>`;
    } catch (e) {
      return `<pre class="hljs"><code>${codeContent}</code></pre>`;
    }
  });

  return rendered;
};
